//
//  ZipLib.m
//  TotemDestroyer
//
//  Created by jobs mac on 09-5-7.
//  Copyright __MyCompanyName__ 2009. All rights reserved.
//

#import "ZipLib.h"

@implementation ZipLib

-(NSData*) DMCompress:(NSData *)data 
{
    NSData *result = NULL;
    if( data ) 
	{
		uLong srcLength = [data length];
		uLongf buffLength = srcLength  * 1.001 + 12;
		NSMutableData *compData = [[NSMutableData alloc]
								   initWithCapacity:buffLength+sizeof(uLong)];
		[compData appendBytes:&srcLength length:sizeof(uLong)];
		[compData increaseLengthBy:buffLength];
		int error = compress( (Bytef*)[compData mutableBytes] + sizeof(uLong),
							 &buffLength,
							 (Bytef*)[data bytes], srcLength );
		switch( error ) 
		{
			case Z_OK:
				[compData setLength:buffLength+sizeof(uLong)];
				result = [compData copy];
				break;
			default:
				NSCAssert( YES, @"Error compressing: Memory Error!" );
				break;
		}
		[compData release];
    }
    return [result autorelease];
}

-(NSData*) DMDecompress:(NSData *)data 
{
    NSData *result = NULL;
    if( data )
	{
		uLongf destLen;
		[data getBytes:&destLen length:sizeof(uLong)];
		NSMutableData *decompData = [[NSMutableData alloc]
									 
									 initWithLength:destLen];
		int error = uncompress( (Bytef*)[decompData mutableBytes], &destLen,
							   (Bytef*)[data bytes]+sizeof(uLong), [data length]-sizeof(uLong) );
		switch( error ) 
		{
			case Z_OK:
				result = [decompData copy];
				break;
			case Z_DATA_ERROR:
				NSCAssert( YES, @"Error decompressing: Corrupt Data!" );
				break;
			default:
				
				NSCAssert( YES, @"Error decompressing: Memory Error!" );
				break;
		}
		[decompData release];
    }
    return [result autorelease];
}
@end
